from django import template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.views.decorators.cache import never_cache
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from oca.views import contest
from oca.forms import RegistrationForm, PasswordChangeForm
from oca.models import User

def profile(request, username):
    user = get_object_or_404(User, username=username)
    return render_to_response('oca/user_page.html', {'usuario':user},
                              context_instance=template.RequestContext(request))

@never_cache
def main_page(request):
    contests = contest.listar_competencias_proximas()
    users = contest.listar_usuarios()
    solutions = contest.listar_soluciones()
    dictContext = {'title': _('Sitio Open Contest Arena'),
                   'contests': contests,
                   'users': users,
                   'solutions': solutions}
    return render_to_response('oca/index.html', dictContext,
                              context_instance=template.RequestContext(request))

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')

def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.clean_data['username'],
                email=form.clean_data['email'],
                password=form.clean_data['password1']
                )
            return HttpResponseRedirect('success/')
    else:
        form = RegistrationForm()
    variables = RequestContext(request, {'form': form})
    return render_to_response('registration/register.html',variables)

@login_required
def password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request, request.POST)
        if form.is_valid():
            request.user.set_password(form.clean_data['newpassword1'])
            request.user.save()
            return HttpResponseRedirect("/")
    else:
        form = PasswordChangeForm(None)
    variables = RequestContext(request,{'form': form})
    return render_to_response('registration/password_change_form.html', variables)